﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.SessionState;

namespace Starry.SmartAjax
{
    /// <summary>
    /// 处理程序
    /// </summary>
    public abstract class BizHandler : IHttpHandler, IRequiresSessionState
    {
        /// <summary>
        /// 处理方法
        /// </summary>
        /// <param name="context">HTTP上下文</param>
        public virtual void ProcessRequest(HttpContext context)
        {
            var bizResult = new BizResult();
            var bizEntity = default(IBizEntity);
            IBizTranscation trans = null;
            try
            {
                bizEntity = this.BizFactory.CreateBizEntity(context);
                bizEntity.HttpContext = context;
                if (bizEntity is ITransactable)
                {
                    trans = bizEntity.BeginBizTranscation();
                    bizEntity.BizTranscation = trans;
                }
                bizResult = bizEntity.Execute();
                if (trans != null)
                {
                    if (bizResult.IsSuccess)
                    {
                        trans.Commit();
                    }
                    else
                    {
                        trans.Rollback();
                    }
                }
            }
            catch (Exception exception)
            {
                bizResult.IsSuccess = false;
                if (this.ExceptionMessageVisible)
                {
                    bizResult.Messages.Add(exception.Message);
                }
                else
                {
                    bizResult.Messages.Add("系统出错，请联系系统管理员！");
                }
                if (trans != null)
                {
                    trans.Rollback();
                }
                this.RecordException(exception);
            }
            finally
            {
                bizResult.Response(context);
            }
        }
        /// <summary>
        /// 记录异常
        /// </summary>
        /// <param name="exception"></param>
        protected virtual void RecordException(Exception exception) { }
        /// <summary>
        /// 获取该程序是否可重用
        /// </summary>
        public virtual bool IsReusable { get { return true; } }
        /// <summary>
        /// 获取该程序的业务工厂
        /// </summary>
        protected abstract IBizFactory BizFactory { get; }
        /// <summary>
        /// 获取异常消息的可见性
        /// </summary>
        protected virtual bool ExceptionMessageVisible { get { return false; } }
    }
}